/*
 * (#)UserDetailService.java 1.0  2013年7月15日 GMT+08:00
 */
package com.newtouch.web.security;

/**
 * @author 凌蒙
 * @version V1.0, 2013年7月15日 GMT+08:00
 * @since JDK1.6
 */
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.newtouch.model.FASRole;
import com.newtouch.model.FASUser;
import com.newtouch.service.FASRoleService;
import com.newtouch.service.FASUserService;

public class UserDetailService implements UserDetailsService  {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(UserDetailService.class);
	//@Inject
	//com.alcor.acl.component.User user ; 
	@Autowired
	 	FASUserService fASUserService;
	@Autowired
 	    FASRoleService fASRoleService;
	
	public UserDetails loadUserByUsername(String username)throws UsernameNotFoundException, DataAccessException {
		if (logger.isDebugEnabled()) {
			logger.debug("loadUserByUsername(String) - start"); //$NON-NLS-1$
		}
			
			Collection<GrantedAuthority> auths=new ArrayList<GrantedAuthority>();
			
			String password=null;
			//取得用户的密码
			FASUser tUser = fASUserService.findFASUserByName(username);
			if (tUser ==null){
				String message = "用户"+username+"不存在";
				logger.error(message);
				throw new UsernameNotFoundException(message);
			}
			password=tUser.getUserPass();
			
			//获得用户的角色
			List<FASRole> tRoles =fASRoleService.findFASRolesByUserName(username);
			for(FASRole item : tRoles){
				GrantedAuthorityImpl grantedAuthorityImpl = new GrantedAuthorityImpl(item.getRoleName());
				if (logger.isDebugEnabled()){
					logger.debug("用户：["+tUser.getUserName()+"]拥有角色：["+item.getRoleName()+"],即spring security中的access");
				}
				auths.add(grantedAuthorityImpl);
			}
			
	        User user = new User(username,password, true, true, true, true, auths);
	        
		if (logger.isDebugEnabled()) {
			logger.debug("loadUserByUsername(String) - end"); //$NON-NLS-1$
		}
	        return user;
	}
}

